{% extends 'envs_python/layout_envs_python.html' %}

{% block html_js_code %}
{{ block.super }}
<script>
layui.use(function(){
  var $ = layui.$;
  var layer = layui.layer;
  var util = layui.util;

function parseXHRError(xhr) {
    let message = '未知错误';

    try {
        const response = JSON.parse(xhr.responseText);
        if (response && response.message) {
            message = response.message;
        } else if (xhr.statusText) {
            message = xhr.statusText;
        }
    } catch (e) {
        if (xhr.statusText) {
            message = xhr.statusText;
        }
        console.error('无法解析错误响应:', xhr.responseText);
    }

    return message;
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

  util.on('lay-on', {
    'iframe_select_folder': function(){
      layer.open({
        title:"选择文件/文件夹",
        type: 2,
        area: ['800px', '600px'],
        content: '{% url 'sharedkit:picker_file_dir' 'dir' %}',
        fixed: false, // 不固定
        maxmin: true,
        shade: 0.5,
        shadeClose: false,
        btn: ['选中', '取消'],
        btnAlign: 'c',
        yes: function(index, layero){
          var iframeWin =  window[layero.find('iframe')[0]['name']];
          var elemMark = iframeWin.$('#picker_path'); // 获得 iframe 中某个输入框元素
          var value = elemMark.val();
          if($.trim(value) === '') return elemMark.focus();
          $('#id_folder').val(value);
          layer.closeAll();
        }
      });
    },
    'set_user_folder': function(){
        $('#id_folder').val("{{ get_user_folder }}");
    },
    'startinstall': function (){
        var loadIndex = layer.msg('下载Python安装包...', {
            icon: 16,
            shade: 0.01,
            time: 0,
            shade: 0.6,
        });

        $.ajax({
            url: '{% url  'envs_python_installer:python_download' %}',
            type: 'POST',
            data: {
                version: $('#id_version').val(),
                folder: $('#id_folder').val(),
                download_source: $('#id_download_source').val(),
            },
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
            },
            success: function (response) {
                layer.close(loadIndex);
                layer.msg('下载成功~开始安装....', {icon: 1, shade: 0.6});

                $.ajax({
                    url: '{% url  'envs_python_installer:python_run_install' %}',
                    type: 'POST',
                    data: {
                        version: $('#id_version').val(),
                        folder: $('#id_folder').val(),
                        {#download_source: $('#id_download_source').val(),#}
                    },
                    headers: {
                        'X-CSRFToken': getCookie('csrftoken'),
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            location.href = '{% url 'envs_python_installer:python_list' %}'
                        }
                    },
                    error: function (xhr, status, error) {
                        let errorMsg = '安装失败: ';
                        const message = parseXHRError(xhr);
                        layer.msg(errorMsg + message, {icon:2});
                    }
                })

            },
            error: function (xhr, status, error) {
                let errorMsg = '下载失败: ';
                const message = parseXHRError(xhr);
                layer.msg(errorMsg + message, {icon:2});
            }
        });
    }
  })
});
</script>
{% endblock %}

{% block page_content %}
{{ block.super }}
<div class="card">
 <form method="post" class="form-horizontal">{% csrf_token %}
    <div class="card-body">
    <div class="form-group row">
      <label class="col-sm-2 col-form-label">{{form.version.label }}</label>
      <div class="col-sm-5">
        {{ form.version }}
      </div>
    </div>

    <div class="form-group row mb-0">
        <label class="col-sm-2 col-form-label">{{ form.folder.label }}</label>
        <div class="col-sm-10">
            <div class="input-group mb-3">
              {{ form.folder }}
              <div class="input-group-append">
<span class="input-group-text hand-cursor" lay-on="iframe_select_folder"><i class="fas fa-folder-open"></i></span>
<span class="input-group-text hand-cursor" lay-on="set_user_folder">用户目录</span>
              </div>
            </div>
        </div>
    </div>

    <div class="form-group row">
      <label class="col-sm-2 col-form-label">{{form.download_source.label }}</label>
      <div class="col-sm-5">
        {{ form.download_source }}
      </div>
    </div>
    </div>
     <div class="card-footer">
         <button type="button" class="btn btn-primary" lay-submit lay-on="startinstall">下载安装</button>
     </div>
 </form>
</div>
{% endblock %}